:- module(_,[(:=)/2],[.(package_ops)]).

:- use_module(library(aggregates)).

:- use_module(db(database_impl)).
:- use_module(library(sort), [sort/2]).
:- use_module(db(basic_types),[null/1]).

%% -------------------------------------------------------

':='(Pkg,Precs ==> Posts):-
%	bagof(Post,retrieve(identificationtags(Pkg,Post)),Posts0),
%	bagof(Prec,retrieve(requires(Pkg,Prec)),Precs0),
	retrieve(Pkg,resource(Pkg,_,_,_,_,_)),
	get_posts(Pkg,Posts0),
	get_precs(Pkg,Precs0),
	sort(Precs0,Precs), % results might be not sorted.
	sort(Posts0,Posts).

%% get_posts(?Pkg,?Posts0)
get_posts(Pkg,Posts):-
	bagof( Post, Post0^Streaming^(
					 retrieve(identificationtags(Pkg,Post0,Streaming)),
					 ( null(Streaming) ->
					   Post = Post0
					 ; functor(Post,Streaming,1),
					   arg(1,Post,Post0)
					 )
				     ),Posts), !.
get_posts(_Pkg,[]). % bagof fails if the list is empty!
	

%% get_precs(+Pkg,?Precs0)
get_precs(Pkg,Precs):-
	bagof( Prec, Prec0^Streaming^(
					 retrieve(requires(Pkg,Prec0,Streaming)),
					 ( null(Streaming) ->
					   Prec = Prec0
					 ; functor(Prec,Streaming,1),
					   arg(1,Prec,Prec0)
					 )
				     ), Precs), !.
get_precs(_Pkg,[]). % bagof fails if the list is empty!



%% -------------------------------------------------------


